package cn.tx.doubaodemo.controller;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

@RestController
@RequestMapping("/chat/stream")
public class StreamChatController {

    @GetMapping(value = "/doubao",produces = "text/plain;charset=UTF-8")
    public ResponseBodyEmitter getDoubaoAnswerStream() {
        final ResponseBodyEmitter emitter = new ResponseBodyEmitter(120 * 1000L);
        new Thread(() -> {
            for (int i = 0; i < 300; i++) {
                try {
                    System.out.println("发发发" + i);
                    emitter.send(String.format("发发发%d", i), MediaType.TEXT_PLAIN);
                    Thread.sleep(50);
                } catch (Exception e) {
                    e.printStackTrace();
                    emitter.completeWithError(e);
                    return;
                }
            }
            emitter.complete();
        }).start();
        return emitter;
    }


}
